package com.chatplus.application.config.ws.interceptor;

import cn.dev33.satoken.exception.NotLoginException;
import com.chatplus.application.web.satoken.helper.LoginHelper;
import com.chatplus.application.web.satoken.model.LoginUser;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket握手请求的拦截器
 */
@Component
public class PlusWebSocketInterceptor implements HandshakeInterceptor {
    /**
     * 握手前
     *
     * @param request    domain
     * @param response   response
     * @param wsHandler  wsHandler
     * @param attributes attributes
     * @return 是否握手成功
     */
    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Map<String, Object> attributes) {
        // 提取 GET 参数
        Map<String, String> params = extractParamsFromURL(request.getURI().getQuery());
        String token = params.get("token");
        attributes.put("session_id", params.get("session_id"));
        attributes.put("chat_id", params.get("chat_id"));
        attributes.put("role_id", params.get("role_id"));
        attributes.put("model_id", params.get("model_id"));
        attributes.put("token", params.get("token"));
        LoginUser loginUser = LoginHelper.getLoginUser(token);
        if (loginUser == null) {
            throw new NotLoginException(NotLoginException.DEFAULT_MESSAGE, "", "");
        }
        attributes.put("userId", loginUser.getUserId());
        return true;
    }

    /**
     * 握手后
     *
     * @param request   domain
     * @param response  response
     * @param wsHandler wsHandler
     * @param exception 异常
     */
    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Exception exception) {

    }

    // 从 URL 链接中提取参数
    private Map<String, String> extractParamsFromURL(String url) {
        Map<String, String> map = new HashMap<>();
        String[] keyValues = url.split("&");
        for (String keyValue : keyValues) {
            String key = keyValue.substring(0, keyValue.indexOf("="));
            String value = keyValue.substring(keyValue.indexOf("=") + 1);
            map.put(key, value);
        }
        return map;
    }
}
